﻿using System;
using System.Collections.Generic;
using Inovout.Descriptor;

namespace Inovout.Security
{
    [Serializable]
    public class SystemRole : IRole
    {
        private static readonly IDictionary<Guid, SystemRole> roleDictionary;
        static SystemRole()
        {
            roleDictionary = new Dictionary<Guid, SystemRole>();
            EnumDescriptor enumDescriptor = new EnumDescriptor(typeof(SystemRoleType));
            foreach (var enumItemDescriptor in enumDescriptor.EnumItems)
            {
                SystemRole role =  new SystemRole((SystemRoleType)enumItemDescriptor.Value,
                    enumItemDescriptor.Alias);
                roleDictionary.Add(role.RoleId, role);
            }
        }
        private Guid roleId;
        public Guid RoleId
        {
            get { return roleId; }
        }

        private string name;
        public string Name
        {
            get { return name; }
        }
        private SystemRoleType type;
        public SystemRoleType Type
        {
            get { return type; }
        }
        internal SystemRole(SystemRoleType type, string name)
        {
            ArgumentGuard.IsNotNullOrEmptyString(name, "name");
            this.name = name;
            this.type = type;
            this.roleId = GetSystemRoleId(type);
        }

        internal static SystemRole GetRole(Guid roleId)
        {
            ArgumentGuard.IsNotEmptyGuid(roleId, "roleId");
            if (roleDictionary.ContainsKey(roleId))
            {
                return roleDictionary[roleId];
            }
            else
            {
                return null;
            }
        }
        public static SystemRole GetRole(SystemRoleType systemRoleType)
        {
            return GetRole(GetSystemRoleId(systemRoleType));
        }

        private static Guid GetSystemRoleId(SystemRoleType systemRoleType)
        {
            return Guid.Parse("00000000-0000-0000-0000-" + ((int)systemRoleType).ToString("000000000000"));
        }
    }
}
